package com.daxia.ogmall.web.controller.admin;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.ogmall.dto.JsonResultDTO;
import com.daxia.ogmall.dto.SeedDTO;
import com.daxia.ogmall.service.SeedService;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.web.controller.BaseController;

@Controller
@RequestMapping(value = "/admin/seed", produces="text/html;charset=UTF-8")
public class AdminSeedController extends BaseController {

	@Autowired
	private SeedService seedService;

	@RequestMapping(value = "/detail")
	public String detail(Map<String, Object> map, Long id) {
		if (id != null) {
			SeedDTO dto = seedService.load(id);
			map.put("n", dto);
		}
		return "admin/seed/seed_detail";
	}
	
	@ResponseBody
	@RequestMapping(value = "/save")
	
	public String save(SeedDTO dto, JsonResultDTO resultDTO) throws Exception {
		if (dto.getId() == null) {
			seedService.create(dto);
		} else {
			seedService.updateAllFields(dto);
		}
		return okAndClose(resultDTO);
	}

    
	@ResponseBody
	@RequestMapping(value = "/delete") 
	public String delete(Long[] ids, JsonResultDTO resultDTO) throws IOException {
		seedService.deleteByIds(ids);
		return okAndRefresh(resultDTO);
	}
	
	@RequestMapping(value = "/list")
	
	public String list(SeedDTO dto, Map<String, Object> map, Page page) {
		List<SeedDTO> dtos = seedService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		return "admin/seed/seed_list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/datagrid")
    
    public String datagrid(SeedDTO dto, Map<String, Object> map, Page page) throws Exception {
        List<SeedDTO> dtos = seedService.find(dto, page);
        JSONArray jsonArray = new JSONArray();
        for (SeedDTO seed : dtos) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", seed.getId());
	        jsonObject.put("user.nickName", seed.getUser().getNickName());    	
            jsonObject.put("name", seed.getName());
            jsonObject.put("mobile", seed.getMobile());
            jsonObject.put("communityName", seed.getCommunityName());
            jsonObject.put("houseType", seed.getHouseType());
            jsonObject.put("area", seed.getArea());
            jsonObject.put("createTime", seed.getCreateTime());
            jsonArray.add(jsonObject);
        }
        JSONObject json = new JSONObject();
        json.put("total", page.getTotalRecords());
        json.put("rows", jsonArray);
        return json.toJSONString();
    }
}
